//
//  EmojiKeyBoardController.swift
//  表情键盘
//
//  Created by Jacky Sun on 16/5/24.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SnapKit

class EmojiKeyBoardController: UIViewController {
    
    
    
    var packageArr: [EmoticonPackage]?{
        didSet{
            collectionView.reloadData()
        }
    }
    
    //声明一个闭包
    var ClickEmotionGetBack: (emotion: Emotion) ->()

    init(emotion: (emotion: Emotion) ->()){
         self.ClickEmotionGetBack = emotion
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
         setUpUI()
    
        packageArr = EmoticonPackage.packageList
    }
   
    private func setUpUI(){
       view.addSubview(toolbar)
      view.addSubview(collectionView)
     collectionView.backgroundColor = UIColor.whiteColor()
     collectionView.dataSource = self
     collectionView.delegate = self
        
    toolbar.snp_makeConstraints { (make) in
    make.left.right.bottom.equalTo(view)
    make.height.equalTo(44)
    collectionView.snp_makeConstraints(closure: { (make) in
        make.left.top.right.equalTo(view)
         make.bottom.equalTo(toolbar.snp_top)
    })
        
      collectionView.registerClass(EmojiCell.self, forCellWithReuseIdentifier: "xxx")
        }
    }
    
    //MARK: - 键盘底部的工具条 toolbar
    func itemsClick(item: UIBarButtonItem){
        
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection:item.tag), atScrollPosition: .Left, animated: false)
    }
    
    private lazy var toolbar: UIToolbar = {
       let tools = UIToolbar()
        tools.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        for title in ["最近", "默认", "emoji", "浪小花"]{
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(EmojiKeyBoardController.itemsClick(_:)))
             item.tag = index
            index += 1
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        // 删除最后一根弹簧
      items.removeLast()
        tools.items = items
            return tools
    }()

    
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmojiLayout())
}

// MARK: - 数据源方法
extension EmojiKeyBoardController: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packageArr?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
          let emotionPackage = packageArr![section] as EmoticonPackage
          let dictArr = emotionPackage.emoticons
        return dictArr?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("xxx", forIndexPath: indexPath) as! EmojiCell
       
        let emotionPackage = packageArr![ indexPath.section]
        let emotion = emotionPackage.emoticons![indexPath.item]
        cell.emotion = emotion
       // cell.backgroundColor = indexPath.item%2 == 0 ? UIColor.brownColor() : UIColor.cyanColor()
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
     
        let emotion = packageArr![indexPath.section].emoticons![indexPath.item]
        // 添加此表情到最新表情
        let recentPackage = packageArr![0]
        recentPackage.addRecentEmotion(emotion)
        
        //调用闭包
        ClickEmotionGetBack(emotion: emotion)
        collectionView.reloadData()
       // print("\(indexPath.section)组， \(indexPath.item)个")
    }
}


class EmojiLayout: UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        // 设置cell的属性
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        let width = UIScreen.mainScreen().bounds.size.width / 7.0
        itemSize = CGSize(width: width, height: width)
        scrollDirection = .Horizontal
        
        // 设置collectionview的属性
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    
        let insetHeight = (collectionView!.frame.size.height - width * 3) * 0.4999
        collectionView?.contentInset = UIEdgeInsets(top: insetHeight, left: 0, bottom: insetHeight, right: 0)
    }
}

class EmojiCell: UICollectionViewCell{
    
    var emotion: Emotion?{
        didSet
        {
            //是不是图片表情
            if emotion!.chs != nil
            {
                imgBtn .setImage(UIImage(named: emotion!.imgPath!), forState: .Normal)
            }
            else
            {// 是emoji表情
                imgBtn.setImage(nil, forState: .Normal)
            }
            
            imgBtn .setTitle(emotion!.emojiStr ?? "", forState: .Normal)
            
            // 3.判断是否是删除按钮
            if emotion!.ISDeleteBtn
            {
                imgBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                imgBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        imgBtn.backgroundColor = UIColor.whiteColor()
        contentView.addSubview(imgBtn)
        imgBtn.frame = CGRectInset(contentView.frame, 4, 4)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private lazy var imgBtn: UIButton = {
       let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        btn.userInteractionEnabled = false
        return btn
    }()
    
}
